package me.xiaoyan.android.tuition.activity;

import java.util.HashMap;
import java.util.Map;

import me.xiaoyan.android.net.AsyncImageLoader;
import me.xiaoyan.android.net.AsyncImageLoader.ImageCallback;
import me.xiaoyan.android.tuition.R;
import me.xiaoyan.android.tuition.utils.AppManager;
import me.xiaoyan.android.tuition.utils.SESHttp;
import me.xiaoyan.android.tuition.utils.TuitionException;
import me.xiaoyan.android.tuition.utils.UnionPay;
import me.xiaoyan.android.widget.BaseUtil;
import me.xiaoyan.android.widget.DataBackListener;
import me.xiaoyan.android.widget.YLog;
import me.xiaoyan.json.JSONArray;
import me.xiaoyan.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class OrderInfo extends Common implements OnClickListener {
	private static final String LOG_TAG = "Activity.OrderInfo";
	private ProgressDialog pd = null;
	private String feedId = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_orderinfo);

		findViewById(R.id.btn_orderinfo_pay).setOnClickListener(this);

		if (!AppManager.getInstance().hasAppDatas(PAY_INFO)
				|| null == AppManager.getInstance().getAppDatas(PAY_INFO)) {
			showToast(getString(R.string.pay_info_null), Toast.LENGTH_SHORT);
			return;
		}
		JSONObject json = (JSONObject) AppManager.getInstance().getAppDatas(
				PAY_INFO);
		feedId = json.optString("feeId");

		setText(R.id.txt_order_school_name, json.optString("schoolName"));
		setText(R.id.txt_order_stu_name, json.optString("studentName"));

		setText(R.id.txt_order_item_name, json.optString("tuitionItemName"));
		double amount = json.optDouble("amount") / 100;
		setText(R.id.txt_order_item_amount, "￥" + amount);
		setText(R.id.txt_order_stu_no, json.optString("studentNo"));

		String status = "未缴费";
		if (json.optInt("status") == 1) {
			findViewById(R.id.btn_orderinfo_pay).setVisibility(View.GONE);
			status = "已缴费";
		}
		setText(R.id.txt_order_pay_status, status);

		final int imageWidth = BaseUtil.dip2px(this,
				BaseUtil.getPhoneWidthPixle(this) - 20);
		AsyncImageLoader imgLoader = new AsyncImageLoader();
		imgLoader.getBitMap(json.optString("schoolUrl"), new ImageCallback() {

			@Override
			public void imageLoaded(Bitmap drawable) {
				// 设置图片
				((ImageView) findViewById(R.id.img_orders_school_img))
						.setImageBitmap(BaseUtil
								.zoomImage(imageWidth, drawable));
			}
		});

	}

	private void setText(int resId, String text) {
		((TextView) findViewById(resId)).setText(text);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_orderinfo_pay) {
			if (!AppManager.getInstance().hasAppDatas(CUSTOMER_ID)) {
				showToast(getString(R.string.must_login_todo),
						Toast.LENGTH_SHORT);
				startActivity(new Intent(this, Login.class));
				return;
			}
			/**
			 * transData:{ feeId:feedId, customerId:Application.data.customerid
			 * }, transUrl:"tuitionFee/createBill"
			 */
			createOrder();
		}
	}

	private void createOrder() {
		Map<String, Object> param = new HashMap<String, Object>();
		Map<String, Object> param1 = new HashMap<String, Object>();

		param1.put("feeId", feedId);
		param1.put("customerId",
				AppManager.getInstance().getAppDatas(CUSTOMER_ID).toString());

		param.put("transData", param1);
		param.put("transUrl", TANSURL);

		pd = getProgress(getString(R.string.creating_order), false);

		SESHttp.sendRequest(CREATE_ORDER, param, new DataBackListener() {

			@Override
			public void success(String source) {
				System.out.println("DataBackListener" + source);
				try {
					JSONArray json = checkSESData(source);
					if (json.length() > 0) {
						String orderId = json.getJSONObject(0).optString(
								"orderId");
						getUnionPayTN(orderId);
					} else {
						showToast(getString(R.string.load_data_failed),
								Toast.LENGTH_SHORT);
					}
				} catch (Exception e) {
					pd.dismiss();
					showToast(
							getString(R.string.load_data_failed)
									+ e.getMessage(), Toast.LENGTH_SHORT);
				}

			}

			@Override
			public void failed(TuitionException e) {
				pd.dismiss();
				YLog.e("payForFee", e);
			}
		});
	}

	private void getUnionPayTN(String orderId) {
		Map<String, Object> param = new HashMap<String, Object>();

		param.put("customerId",
				AppManager.getInstance().getAppDatas(CUSTOMER_ID).toString());
		param.put("orderId", orderId);
		param.put("paymentId", PAYMENT_ID);
		SESHttp.sendRequest(GET_UNIONPAY_TN, param, new DataBackListener() {

			@Override
			public void success(String source) {
				System.out.println("DataBackListener" + source);
				if (pd != null) {
					pd.dismiss();
				}
				try {
					JSONArray json = checkSESData(source);
					if (json.length() > 0) {
						String unionPaTN = json.getJSONObject(0).optString(
								"payData");
						new UnionPay().payUsTN(unionPaTN, OrderInfo.this);
					} else {
						showToast(getString(R.string.load_data_failed),
								Toast.LENGTH_SHORT);
					}
				} catch (Exception e) {
					showToast(
							getString(R.string.load_data_failed)
									+ e.getMessage(), Toast.LENGTH_SHORT);
				}
			}

			@Override
			public void failed(TuitionException e) {
				if (pd != null) {
					pd.dismiss();
				}
				YLog.e("payForFee", e);
			}
		});
	}

	@Override
	public void onBackPressed() {
		goback();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == LOGIN_SUCCESS_BACK) {
			createOrder();
		} else {
			if (data == null) {
				Log.v(LOG_TAG, "Activity result is null");
				return;
			}

			/*
			 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
			 */
			String str = data.getExtras().getString("pay_result");
			Log.i(LOG_TAG, "Activity result is " + str);
			if (str.equalsIgnoreCase("success")) {
				showToast(getString(R.string.pay_sucess), Toast.LENGTH_SHORT);
				gobackHome();
				Log.i(LOG_TAG, "支付成功！(Pay success)");
			} else if (str.equalsIgnoreCase("fail")) {
				showToast(getString(R.string.pay_failed), Toast.LENGTH_SHORT);
				Log.i(LOG_TAG, "支付失败！(Pay failed)");
			} else if (str.equalsIgnoreCase("cancel")) {
				showToast(getString(R.string.cancel_pay), Toast.LENGTH_SHORT);
				Log.i(LOG_TAG, "用户取消了支付！(cancel the pay)");
			}
		}

	}
}
